package com.fifa.maroc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;


public class AllActualitesActivity extends ListActivity{
    /** Called when the activity is first created. */
	static String contunue;
	 private ProgressDialog pDialog;
	 ListView lv ;
	 ListView list;
	 ImageView img;
	 //creation une instence de class JSONParser
	 JSONParser jParser=new JSONParser();
	 
	 ArrayList<HashMap<String, String>> actualitesList;
	 // url pour avoir la liste des actualites
	 private static String url_all_actualites="http://10.0.2.2/and_connect/get_all_actualite.php";
	 
	 // les noms de json nodes
	    static final String TAG_SUCCESS = "success";
	     static final String TAG_ACTUALITES = "actualite";
	     static final String TAG_AID = "aid";
	    static final String TAG_TITRE = "titre";
	   static final String TAG_CONTENU = "contenu";
	     static final String TAG_CATEGORIE = "categorie";
	    static final String TAG_DATE = "date_act";
	    
	 //  JSON table actualities
	    JSONArray actualites = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_actualites);
        actualitesList = new ArrayList<HashMap<String, String>>();
        new LoadAllActualites().execute();
        ListView lv = getListView();
        
        // on seleting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new OnItemClickListener() {
 
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String aid = ((TextView) view.findViewById(R.id.aid)).getText()
                        .toString();
                String titre = ((TextView) view.findViewById(R.id.title)).getText()
                        .toString();
                String date= ((TextView) view.findViewById(R.id.time)).getText()
                        .toString();
                
 
                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        DetaillesActActivity.class);
                // sending pid to next activity
                in.putExtra(TAG_AID, aid);in.putExtra(TAG_TITRE, titre);
                in.putExtra(TAG_DATE, date);
               in.putExtra(TAG_CONTENU, contunue);
           
                // starting new activity and expecting some response back
                startActivityForResult(in, 100);
            }
        });
    }
    /**
     * Background Async Task to Load all actus by making HTTP Request
     * */
    class LoadAllActualites extends AsyncTask<String, String, String> {

		@Override
		protected void onPreExecute() {
			
			
			  super.onPreExecute();
	            pDialog = new ProgressDialog(AllActualitesActivity.this);
	            pDialog.setMessage("Loading actualites. Please wait...");
	            pDialog.setIndeterminate(false);
	            pDialog.setCancelable(false);
	            pDialog.show();
		}

		@Override
		protected String doInBackground(String... args) {
			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			// getting JSON string from URL
			JSONObject json = jParser.makeHttpRequest(url_all_actualites, "GET", params);
			
			// Check your log cat for JSON reponse
			Log.d("All actualities: ", json.toString());

			try {
				// Checking for SUCCESS TAG
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					// products found
					// Getting Array of Products
					actualites = json.getJSONArray(TAG_ACTUALITES);

					// looping through All Products
					for (int i = 0; i < actualites.length(); i++) {
						JSONObject c = actualites.getJSONObject(i);

						// Storing each json item in variable
					//	String id = c.getString(TAG_AID);
						String titre = c.getString(TAG_TITRE);
                        String categorie=c.getString(TAG_CATEGORIE);
                        String time=c.getString(TAG_DATE);
                        contunue=c.getString(TAG_CONTENU);
                        
						// creating new HashMap
						HashMap<String, String> map = new HashMap<String, String>();

						// adding each child node to HashMap key => value
						//map.put(TAG_AID, id);
						map.put(TAG_TITRE, titre);
						map.put(TAG_CATEGORIE, categorie);
						map.put(TAG_DATE, time);
						//map.put("img", String.valueOf(R.drawable.foot));

						// adding HashList to ArrayList
						actualitesList.add(map);
						
						//Log.d("All actualities: ", "Fin doInBaground");
					}
				} else {
					// no products found
					// Launch Add New product Activity
					Intent i = new Intent(getApplicationContext(),
							NofoundactualiteActivity.class);
					// Closing all previous activities
					i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(i);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		 protected void onPostExecute(String file_url) {
	            // dismiss the dialog after getting all products
	            pDialog.dismiss();
	            // updating UI from Background Thread
	            runOnUiThread(new Runnable() {
					public void run() {
						/**
						 * Updating parsed JSON data into ListView
						 * */
						ListAdapter adapter = new SimpleAdapter(AllActualitesActivity.this, actualitesList,R.layout.list_item, new String[] { TAG_TITRE,TAG_CATEGORIE,TAG_DATE},
								new int[] { R.id.title, R.id.categoie, R.id.time });
						// updating listview
						setListAdapter(adapter);
					}
				});
	 
	        }
    }}